package leetcode.binarytree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的中序遍历 简单
 */
public class Solution94二叉树的中序遍历 {
//    给定一个二叉树的根节点 root ，返回它的 中序 遍历

//    输入：root = [1,null,2,3]
//    输出：[1,3,2]

//    1
//        2
//    3

    //方法一：递归
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorder(root, res);
        return res;
    }

    public void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }


    //方法二：迭代
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();
        while (root != null || !stk.isEmpty()) {
            while (root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);

        TreeNode rightTreeNode = new TreeNode(2);
        treeNode.right = rightTreeNode;

        TreeNode leftTreeNode = new TreeNode(3);
        rightTreeNode.left = leftTreeNode;

        Solution94二叉树的中序遍历 solution94 = new Solution94二叉树的中序遍历();
        solution94.inorderTraversal(treeNode);
    }
}
